package com.sdms.core.util;

import java.security.NoSuchAlgorithmException;

public class PasswordEncryptionUtil
{
//	private static String algorithm = "SHA";
//	private static String algorithm = "SHA-1";
	private static String algorithm = "MD5";

	public static boolean validatePassword( String attemptedPassword, String encryptedPassword ) 
	{
		boolean valiated = false;
		String inputHash;
		try
		{
			inputHash = getEncryptedPassword( attemptedPassword );
			if ( encryptedPassword.equals( inputHash ) )
			{
				valiated = true;
			}
		}
		catch ( NoSuchAlgorithmException e )
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return valiated;
	}
	
	public static String getEncryptedPassword( String password ) throws NoSuchAlgorithmException
	{
		return byteArrayToHexString( getEncryptedByteArray( password ) );
	}

	public static byte[] getEncryptedByteArray( String password ) throws NoSuchAlgorithmException
	{
		java.security.MessageDigest d = null;
		d = java.security.MessageDigest.getInstance( algorithm );
		d.reset();
		d.update( password.getBytes() );
		return d.digest();
	}

	public static String byteArrayToHexString( byte[] b )
	{
		StringBuffer sb = new StringBuffer( b.length * 2 );
		for ( int i = 0; i < b.length; i++ )
		{
			int v = b[i] & 0xff;
			if ( v < 16 )
			{
				sb.append( '0' );
			}
			sb.append( Integer.toHexString( v ) );
		}
		return sb.toString().toUpperCase();
	}
}
